#include "lockctrl.h"
#include <QDebug>
#define DEV_LOCK_CTRL "/dev/ttymxc2"   //底板串口

LockCtrl::LockCtrl(QObject *parent) : QObject(parent)
{
    mycom = NULL;
}

void LockCtrl::initCom(QString devName, int baudRate)
{
    if(mycom != NULL)
        delete mycom;
#if QT_VERSION > 0x50000
    mycom = new QSerialPort(this);
    if(devName.isEmpty())
    {
        QStringList devList = getDevList();
        if(devList.isEmpty())
            return;
        mycom->setPortName(devList.at(0));
        qDebug()<<"[initCom]"<<"open default dev:"<<devList.at(0);
    }
    else
    {
        mycom->setPortName(devName);
        qDebug()<<"[initCom]"<<"open dev:"<<devName;
    }

    if(!mycom->open(QIODevice::ReadWrite))
    {
        emit openDevRst(false);
        return;
    }
    if(baudRate == 0)
        baudRate = 38400;
    mycom->setBaudRate(baudRate);
    mycom->setDataBits(QSerialPort::Data8);
    mycom->setParity(QSerialPort::NoParity);
    mycom->setFlowControl(QSerialPort::NoFlowControl);
    mycom->setStopBits(QSerialPort::OneStop);
    connect(mycom, SIGNAL(readyRead()), this, SLOT(recvComData()));
#else

    mycom = new QextSerialPort(QString(DEV_LOCK_CTRL));
    qDebug()<<"[initCom]"<<"open dev:"<<DEV_LOCK_CTRL;

    if(!mycom->open(QIODevice::ReadWrite))
    {
        emit openDevRst(false);
        return;
    }
//    if(baudRate == 0)
//        baudRate = 38400;
    mycom->setBaudRate(BAUD38400);
    mycom->setDataBits(DATA_8);
    mycom->setParity(PAR_NONE);
    mycom->setFlowControl(FLOW_OFF);
    mycom->setStopBits(STOP_1);
    connect(mycom, SIGNAL(readyRead()), this, SLOT(recvComData()));
#endif

}

void LockCtrl::writeData(QByteArray qba)
{
    qDebug()<<"[LockCtrl]:"<<qba.toHex();
    mycom->write(qba);
}

void LockCtrl::openLock(int cascadeNum, int ioNum)
{
    QByteArray qba = QByteArray::fromHex("fa000100ff");
    qba[1] = cascadeNum;
    qba[3] = ioNum;
    qDebug()<<"[openLock]:"<<qba.toHex();
    mycom->write(qba);
}
#if QT_VERSION > 0x50000
QStringList LockCtrl::getDevList()
{
    QStringList ret;
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        qDebug()<<"Name:"<<info.portName();
        ret<<info.portName();
    }
    qDebug()<<"[devList]"<<ret;
    return ret;
}
#endif
void LockCtrl::recvComData()
{
    qDebug()<<"[recvComData]:"<<mycom->readAll();
}
